import tkinter, re, webbrowser
import tkinter.messagebox as msgbox
import os
import requests
from bs4 import BeautifulSoup
import json
from urllib import parse



"""
说明
    默认下载地址 C盘下创建目录 DY_veido 可适当更改
    只根据分享视频得短链接进行解析下载

"""







class APP:

    # 初始化GUI界面
    def __init__(self, width=500, height=300, title="抖音下载无水印视频"):

        self.width = width
        self.height = height
        self.title = title

        # 创建窗口,设置标题
        self.root = tkinter.Tk(className=self.title)


        # 访问地址保存
        self.url = tkinter.StringVar()  # str

        # 创建容器 Frame 有定位属性，可以把内部的控制按照排版定位
        # frame_1 = tkinter.Frame(self.root)
        frame_2 = tkinter.Frame(self.root)

        # 创建控件
        # 边距：ipad 内部边距 pad 外部边距 默认：像素

        label = tkinter.Label(frame_2, text="输入分享链接")
        entry = tkinter.Entry(frame_2, textvariable=self.url, width=40)

        # font 字体
        # command 指令，可以捆绑一个函数响应
        play = tkinter.Button(frame_2, text="下载视频", font=("黑体", 12), width=5, height=2, command=self.video_play)

        frame_2.pack()

        # 栅格定位

        label.grid(row=1, column=0)
        entry.grid(row=1, column=1)
        play.grid(row=1, column=2, ipadx=10, ipady=10)


    def save_file(self, video_res):
        # 保存视频到本地
        import time
        filename = str(int(time.time() * 1000)) + '.mp4'
        p = 'C:/DY_veido'
        path = os.path.exists(p)
        if not path:
            os.mkdir(p)
        with open('{}'.format(p+ '/'+filename), 'wb')as f:
            f.write(video_res.content)
            print('下载成功')


    # 破解视频
    def video_play(self):
        # 调用接口
        # re.findall()匹配正则，是否满足条件
        re_res = re.findall(r"(https?:/{2}\w.+/)", self.url.get())
        if re_res:
            headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"
            }
            res = re.findall(r"(https?:/{2}\w.+/)", re_res[0])
            res = requests.head(res[0])
            location = res.headers.get('location')
            rrr = requests.get(location, headers=headers)
            soup = BeautifulSoup(rrr.text, 'html.parser')
            script = soup.find('script', attrs={'id': "RENDER_DATA"}).string
            data = parse.unquote(script)
            data = json.loads(data)
            playAddr_list = data['C_12']['aweme']['detail']['video']['playAddr']  # 列表内包含字典 src video_id
            for playaddr in playAddr_list:
                src = playaddr.get('src')
                if src:
                    if re.findall('video_id', src):
                        res_url = 'https:' + src
                        print(res_url)
                        veido_res = requests.get(res_url, headers=headers)
                        self.save_file(veido_res)
                        break
        else:
            msgbox.showerror(title="错误", message="视频地址无效，请重新输入")

    # 启动类
    def run(self):
        # 设置窗口的大小
        self.root.geometry(str(self.width) + "x" + str(self.height))
        # 允许用户控制窗口的大小
        self.root.resizable(width=True, height=True)
        # 启动窗口
        self.root.mainloop()


app = APP()
app.run()
